/*****************************************
 *  所属版本  系统开发平台       *
 *****************************************/
package com.adds.lvds.controller.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.adds.lvds.core.trace.TraceContent;
import com.adds.lvds.core.trace.TraceService;
import com.adds.lvds.model.code.SysCode;
import com.adds.lvds.service.impl.Service;
import com.adds.lvds.service.impl.code.SysCodeSetting;

/**
 * 
 * 项目名称 ：weichat_web
 * 
 * @des 系统服务管理，用于系统服务的初始化，启动，关闭
 * @author zhangjian
 * @time 2017-1-1下午9:32:08
 */
public class ServiceManagerServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2450002972187246091L;
	private List<Service> services = new ArrayList<Service>();
	private boolean isInit;
	private boolean isRun;

	public synchronized void init() throws ServletException {
		startup();
	}

	protected synchronized void service(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		String cmd = req.getParameter("cmd");
		if ("init".equalsIgnoreCase(cmd)) {
			initialize();
		} else if ("startup".equalsIgnoreCase(cmd)) {
			startup();
		} else if ("shutdown".equalsIgnoreCase(cmd)) {
			shutdown();
		} else if ("restart".equalsIgnoreCase(cmd)) {
			shutdown();
			startup();
		}
	}

	public synchronized void destroy() {
		shutdown();
	}

	/**
	 * 
	 */
	private synchronized void initialize() {
		if(SysCodeSetting.getCodeType("SYSTEM_SERVICE")==null){
			TraceService.info(TraceContent.SYSTEM,"系统服务未配置");
			return;
		}
		List<SysCode> codes = SysCodeSetting.getCodeType("SYSTEM_SERVICE").getCodes();
		Service service = null;
		try {
			for (SysCode sysCode : codes) {
				service = (Service) Class.forName(sysCode.getCodeValue()).newInstance();
				this.services.add(service);
				TraceService.info(TraceContent.SYSTEM,"加载系统服务[" + service + "]成功！");
			}

		} catch (Exception e) {
			TraceService.error(TraceContent.SYSTEM,"加载系统服务[" + service + "]失败！", e);
		}

		isInit = true;
	}

	private void startup() {
		if (!isInit && !isRun) {
			initialize();
		}

		if (isInit && !isRun) {
			try {
				for (Service service : services) {
					if (service.initialize()) {
						service.startup();
					}
				}
				isRun = true;
			} catch (Exception e) {
				log("系统服务启动失败！", e);
				isRun = false;
			}
		}
	}

	private void shutdown() {
		if (isRun) {
			for (Service service : services) {
				service.destroy();
			}
			isRun = false;
		}
	}

}
